<template>
  <div class="message-manage">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-select v-model="filter.senderId" placeholder="发送者">
        <el-option label="全部" value=""></el-option>
        <el-option
            v-for="user in usersMap"
            :key="user.id"
            :label="user.username"
            :value="user.id"
        ></el-option>
      </el-select>
      <el-select v-model="filter.receiverId" placeholder="接收者">
        <el-option label="全部" value=""></el-option>
        <el-option
            v-for="user in usersMap"
            :key="user.id"
            :label="user.username"
            :value="user.id"
        ></el-option>
      </el-select>
      <el-select v-model="filter.msgType" placeholder="消息类型">
        <el-option label="全部" value=""></el-option>
        <el-option label="文本" value="text"></el-option>
        <el-option label="图片" value="image"></el-option>
      </el-select>
      <el-button type="primary" @click="fetchMessages">搜索</el-button>
      <el-button @click="resetFilters">重置</el-button>
    </div>

    <!-- 消息列表 -->
    <el-table :data="messages" border stripe style="width: 100%">
      <!-- 消息序号 -->
      <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>

      <!-- 消息ID（隐藏或移除） -->
      <!-- <el-table-column prop="id" label="消息ID" width="80"></el-table-column> -->

      <!-- 发送者 -->
      <el-table-column prop="senderId" label="发送者" width="120">
        <template #default="{ row }">
          {{ getUserById(row.senderId)?.username || '未知' }}
        </template>
      </el-table-column>

      <!-- 接收者 -->
      <el-table-column prop="receiverId" label="接收者" width="120">
        <template #default="{ row }">
          {{ getUserById(row.receiverId)?.username || '未知' }}
        </template>
      </el-table-column>

      <!-- 内容 -->
      <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip></el-table-column>

      <!-- 类型 -->
      <el-table-column prop="msgType" label="类型" width="100">
        <template #default="{ row }">
          {{ row.msgType === 'text' ? '文本' : '图片' }}
        </template>
      </el-table-column>

      <!-- 创建时间 -->
      <el-table-column prop="createdAt" label="创建时间" width="160"></el-table-column>

      <!-- 阅读状态 -->
      <el-table-column label="阅读状态" width="120">
        <template #default="{ row }">
          <el-tag
              :type="row.readStatus ? 'success' : 'danger'"
              disable-transitions
              @click="toggleReadStatus(row)"
          >
            {{ row.readStatus ? '已读' : '未读' }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="text" size="small" @click="editMessage(row)">编辑</el-button>
          <el-button type="text" size="small" @click="deleteMessage(row)">删除</el-button>
          <!-- 如果需要单独的标记已读按钮，可以保留；否则，阅读状态列已经处理 -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          layout="prev, pager, next, jumper"
      ></el-pagination>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog title="编辑消息" v-model="editDialogVisible">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="内容">
          <el-input type="textarea" v-model="editForm.content" autocomplete="off" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox, ElTag} from 'element-plus';
import http from '@/request/Http.js';

const messages = ref([]);
const users = ref([]); // 用户列表
const usersMap = ref({}); // 用户ID到用户名的映射
const filter = reactive({
  senderId: '',
  receiverId: '',
  msgType: ''
});
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});
const editDialogVisible = ref(false);
const editForm = reactive({
  id: null,
  content: ''
});

// 获取用户列表
const fetchUsers = async () => {
  try {
    const res = await http.get('/user/getUser'); // 确保接口路径正确
    console.log('获取用户列表响应:', res);
    if (res.code === 200) {
      users.value = res.data.records || []; // 假设返回的数据结构中有 records 字段
      // 构建用户ID到用户名的映射
      usersMap.value = users.value.reduce((map, user) => {
        map[user.id] = user;
        return map;
      }, {});
      console.log('用户列表:', users.value);
      console.log('用户映射:', usersMap.value);
    } else {
      ElMessage.error(res.msg || '获取用户列表失败');
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败，请稍后重试');
  }
};

// 获取消息列表
const fetchMessages = async () => {
  try {
    const response = await http.get('/comment/getAllMessages', {
      params: {
        senderId: filter.senderId,
        receiverId: filter.receiverId,
        msgType: filter.msgType,
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      }
    });
    console.log('获取消息列表响应:', response);
    if (response.code === 200) {
      messages.value = response.data.records || []; // 假设返回的数据结构中有 records 字段
      // 为每条消息添加序号
      messages.value.forEach((msg, index) => {
        msg.serialNumber = (pagination.currentPage - 1) * pagination.pageSize + index + 1;
      });
      pagination.total = response.data.total || 0;
      pagination.currentPage = response.data.currentPage || 1;
      pagination.pageSize = response.data.pageSize || 10;
    } else {
      ElMessage.error(response.msg || '获取消息列表失败');
    }
  } catch (error) {
    ElMessage.error('获取消息列表失败，请检查网络');
    console.error(error);
  }
};

// 重置过滤器
const resetFilters = () => {
  filter.senderId = '';
  filter.receiverId = '';
  filter.msgType = '';
  fetchMessages();
};

// 编辑消息
const editMessage = (row) => {
  editForm.id = row.id;
  editForm.content = row.content;
  editDialogVisible.value = true;
};

// 提交编辑
const submitEdit = async () => {
  try {
    const res = await http.put(`/comment/editMessage/${editForm.id}`, {
      content: editForm.content
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    if (res.code === 200) {
      ElMessage.success('消息编辑成功');
      fetchMessages();
      editDialogVisible.value = false;
    } else {
      ElMessage.error(res.msg || '消息编辑失败');
    }
  } catch (error) {
    ElMessage.error('消息编辑失败，请重试');
    console.error(error);
  }
};

// 删除消息
const deleteMessage = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除消息 "${row.content}" 吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    });
    const res = await http.delete(`/comment/deleteMessage/${row.id}`);
    if (res.code === 200) {
      ElMessage.success('消息删除成功');
      fetchMessages();
    } else {
      ElMessage.error(res.msg || '消息删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除消息失败或取消操作');
    }
  }
};

// 标记消息为已读
const markAsRead = async (row) => {
  try {
    const res = await http.put(`/comment/markAsRead/${row.id}`);
    if (res.code === 200) {
      ElMessage.success('消息已标记为已读');
      // 更新本地数据
      row.readStatus = true;
    } else {
      ElMessage.error(res.msg || '标记消息为已读失败');
    }
  } catch (error) {
    ElMessage.error('标记消息为已读失败，请重试');
    console.error(error);
  }
};

// 切换阅读状态
const toggleReadStatus = async (row) => {
  if (row.readStatus) {
    ElMessage.info('该消息已读，无法再次标记。');
    return;
  }
  await markAsRead(row);
};

// 分页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  fetchMessages();
};

// 初始化
onMounted(async () => {
  try {
    await fetchUsers();
    await fetchMessages();
  } catch (error) {
    console.error('初始化失败:', error);
    ElMessage.error('初始化失败，请稍后重试');
  }
});

// 定义 getUserById 方法
const getUserById = (id) => {
  return usersMap.value[id];
};
</script>

<style scoped>
.message-manage {
  padding: 20px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>